<?php
class OrderAction extends AdminbaseAction
{

	protected $dao;
    function _initialize()
    {	
		parent::_initialize();
		$this->adminfilepath = TMPL_PATH.$this->sysConfig['DEFAULT_THEME'].'/Public/billtemplate/';


		$this->dao=M('Order');
if($_SESSION['administrator']==1){
$listarr=array(
	'va'=>'网站编号',
	'vb'=>'网站国家',
	'vc'=>'销售员',
	'vd'=>'客户姓名',
	've'=>'客户公司',
	'vf'=>'客户地址',
	'vg'=>'客户邮箱',
	'vh'=>'客户邮编',
	'vi'=>'客户电话',
	'vj'=>'客户留言',
	'vk'=>'发货方式',
	'vl'=>'订单状态',
	'vm'=>'跟踪码',
	'vn'=>'备注',
);
foreach($listarr as $k=>$val){
	$this->assign ( $k, $k );
}
}else{
			$alist = M('role')->where('id = '.$_SESSION['groupid'])->find();
			if(false === strripos($alist['orderfield'],',')){
				$fieldarr = array($alist['orderfield']);
			}else{
				$fieldarr = split ('[,.-]', $alist['orderfield']);
			}
			foreach($fieldarr as $val){
				$this->assign ( $val, $val );
			}
		}
	
}

    public function index()
    {
		$type=  'html';
		$path=$this->adminfilepath;
		$files = dir_list($path,$type);
		foreach ($files as $key=>$file){
			$filename = basename($file);
			$templates[$key]['value'] =  substr($filename,0,strrpos($filename, '.'));
			$templates[$key]['filename'] = $filename;
			$templates[$key]['filepath'] = $file;
			$templates[$key]['filesize']=byte_format(filesize($file));
			$templates[$key]['filemtime']=filemtime($file);
			$templates[$key]['ext'] = strtolower(substr($filename,strrpos($filename, '.')-strlen($filename)));
		}
		$this->assign ( 'templates',$templates );
		$template =  file_exists(TEMPLATE_PATH.'/'.GROUP_NAME.'/'.MODULE_NAME.'_index.html') ? MODULE_NAME.'_index' : 'content_index';
	    $this->_list(MODULE_NAME);
		$this->assign ( 'username', $_GET['username'] );
		$this->assign ( 'website1', M('website') -> select() );
if($_GET['pdf']){
$this->outpdf();
}elseif($_GET['execl']){
$this->execl();
}else{

		$_rs=M('role')->where('id='.$_SESSION['groupid'])->find();
		$this->assign ( 'orderfield',$_rs['orderfield'] );
		//print_r($template);
        $this->display ($template);
}


    }

 	public function edit(){
		$sn = $_REQUEST['sn'];
		$id= $_REQUEST['id'];
		$model =M('Order');
		if($sn){
			$cart = $model->getBySn($sn); 
		}elseif($id){
		   $cart = $model->find($id); 
		}else{
			$this->error ( L('do_empty'));
		}
		$cart['productlist']=unserialize($cart['productlist']);

		foreach((array)$cart['productlist'] as $key =>$rs){
			$cart['totalnum'] +=$rs['num'];
			$cart['totalprice'] += $rs['num']*$rs['price'];
			$cart['productlist'][$key]['countprice'] = $rs['num']*$rs['price'];
		}
		$this->assign('cart',$cart);

		$_rs=M('role')->where('id='.$_SESSION['groupid'])->find();
		$this->assign ( 'orderfield',$_rs['orderfield'] );

		$this->display();
		
	}
	public function show(){
		$sn = $_REQUEST['sn'];
		$id= $_REQUEST['id'];
		$model =M('Order');
		if($sn){
			$cart = $model->getBySn($sn); 
		}elseif($id){
		   $cart = $model->find($id); 
		}else{
			$this->error ( L('do_empty'));
		}
		 
		$cart['productlist']=unserialize($cart['productlist']);

		foreach((array)$cart['productlist'] as $key =>$rs){
			$cart['totalnum'] +=$rs['num'];
			$cart['totalprice'] += $rs['num']*$rs['price'];
			$cart['productlist'][$key]['countprice'] = $rs['num']*$rs['price'];
		}
		$this->assign('cart',$cart);
		$this->display();
		
	}
	function update() {
		$model =M('Order');
		if (false === $model->create ()) {
			$this->error ( $model->getError () );
		}
		if (false !== $model->save ()) {


if($_POST['status']==1){
//如果是发货状态减去库存
	$mo_db=M('Order');
	if($mo_tmp=$mo_db->where('id='.$_POST['id'])->find()){
		$productlist=unserialize($mo_db->productlist);
		$mo_db=M('Stock');
		foreach((array)$productlist as $rs){
			$mo_tmp=$mo_db->setDec('number','productcode="'.$rs['productcode'].'"',$rs['num']);
		}
	}
}
if($_POST['status']==4){
//如果是已付款状态设置标记
	$model->where('id='.$_POST['id'])->setField('ispayment',1);
}
			if(in_array($name,$this->cache_model)) savecache($name);
			$this->success (L('edit_ok'));
		} else {
			$this->success (L('edit_error').': '.$model->getDbError());
		}
	}
	public function outpdf()
	{
		$this->_list(MODULE_NAME);
 //       $this->display ();
include("Yourphp/Lib/tcpdf/config/lang/eng.php");
require_once('Yourphp/Lib/tcpdf/tcpdf.php');
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Mo');
$pdf->SetTitle('订单列表');
$pdf->SetSubject('订单列表');
$pdf->SetKeywords('订单列表');
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH);
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$pdf->setLanguageArray($l);
$pdf->SetFont('stsongstdlight', '', 20);
$pdf->AddPage();
//$pdf->write(0, $this->fetch ($template), '', 0, 'L', true, 0, false, false, 0);
$pdf->writeHTML($this->fetch ('Order_outpdf'), true, 0, true, 0);
$pdf->Output('example_038.pdf', 'I');

	}
	protected function _list($modelname, $map = '', $sortBy = '', $asc = false ,$listRows = 100) {
		$model = M($modelname);
		$id=$model->getPk ();
		$this->assign ( 'pkid', $id );

		if (isset ( $_REQUEST ['order'] )) {
			$order = $_REQUEST ['order'];
		} else {
			$order = ! empty ( $sortBy ) ? $sortBy : $id;
		}
		if (isset ( $_REQUEST ['sort'])) {
			$_REQUEST ['sort']=='asc' ? $sort = 'asc' : $sort = 'desc';
		} else {
			$sort = $asc ? 'asc' : 'desc';
		}
		$website=$_REQUEST['website'];
		$_REQUEST ['sort'] = $sort;
		$_REQUEST ['order'] = $order;
		$keyword=$_REQUEST['keyword'];
		$searchtype=$_REQUEST['searchtype'];
		$groupid =intval($_REQUEST['groupid']);
		$catid =intval($_REQUEST['catid']);
		$posid =intval($_REQUEST['posid']);
		$typeid =intval($_REQUEST['typeid']);
		if(!empty($keyword) && !empty($searchtype)){
			$map[$searchtype]=array('like','%'.$keyword.'%');
		}
		if($website) $map['domain']=$website;
if($_REQUEST['startdate'] && $_REQUEST['enddate']){
//时间查询
		$_REQUEST['startdate']=strtotime($_REQUEST['startdate']);
		$_REQUEST['enddate']=strtotime($_REQUEST['enddate']);
		define('Halfofday',60*60*24-1);
		//$_REQUEST['enddate']=$_REQUEST['enddate']+Halfofday;
		$_REQUEST['enddate']=$_REQUEST['enddate'];
		$map['createtime']=array(array('gt',$_REQUEST['startdate']),array('lt',$_REQUEST['enddate'])) ;
}
		if($groupid)$map['groupid']=$groupid;
		if($catid)$map['catid']=$catid;
		if($posid)$map['posid']=$posid;
		if($typeid) $map['typeid']=$typeid;

		if(isset($_REQUEST['status']) && ( $_REQUEST['status']==='0' || $_REQUEST['status']>0)){
			$map['status']=intval($_REQUEST['status']);
		}else{
			unset($_REQUEST['status']);
		}

		$this->assign($_REQUEST);
		$this->assign('website',$website);
		//取得满足条件的记录总数
		$count = $model->where ( $map )->count ( $id );
		if ($count > 0) {
				import ( "@.ORG.Page" );
				//创建分页对象
				if (! empty ( $_REQUEST ['listRows'] )) {
					$listRows = $_REQUEST ['listRows'];
				}
echo $_REQUEST['a'];
				$p = new Page ( $count, $listRows );
				//分页查询数据

				$field=$this->module[$this->moduleid]['listfields'];
				$voList = $model->field($field)->where($map)->order( "`" . $order . "` " . $sort)->limit($p->firstRow . ',' . $p->listRows)->findAll ( );
				
				foreach($voList as $k=>$val){
					//序列化
					$val['productlist']=unserialize($val['productlist']);
					$voList[$k]['sublist']=$val['productlist'];
				}
				//分页跳转的时候保证查询条件
				foreach ( $map as $key => $val ) {
					if (! is_array ( $val )) {
						$p->parameter .= "$key=" . urlencode ( $val ) . "&";
					}
				}
				$map[C('VAR_PAGE')]='{$page}';
				$page->urlrule = U($modelname.'/index', $map);
				//分页显示
				$page = $p->show ();
				//列表排序显示
				$sortImg = $sort; //排序图标
				$sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
				$sort = $sort == 'desc' ? 1 : 0; //排序方式
				//模板赋值显示
				$this->assign ( 'list', $voList );
				$this->assign ( 'page', $page );
		}
		return;
	}


    public function bill()
    {
		$ids=$_POST['ids'];
		if(!empty($ids) && is_array($ids)){
			$id=implode(',',$ids);
			$tmpdata=M('order')->where('id in ('.$id.')')->select();
			
			
			foreach($tmpdata as $k=>$val){$tmpdata[$k]['sublist']=unserialize($val['productlist']);}
			
			
			
			
			$this->assign ( 'order', $tmpdata );
			foreach($tmpdata as $k=>$val){
				$this->assign ( 'consignee'.$k, $val['consignee'] );
				$this->assign ( 'address'.$k, $val['address'] );
				$this->assign ( 'trackcode'.$k, $val['trackcode'] );
				$tmpdataid=$val['id'];
			}
			
			$data['id']=$tmpdataid;
			$data['status'] = 1;
			$tmpdataedit=M('order');
			$tmpdataedit->save($data);
			//$tmpdataedit->where('id='.$tmpdataid)->data($map)->save();
			include("Yourphp/Lib/tcpdf/config/lang/eng.php");
			require_once('Yourphp/Lib/tcpdf/tcpdf.php');
			$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
			$pdf->SetCreator(PDF_CREATOR);
			$pdf->SetAuthor('Mo');
			$pdf->SetTitle('订单列表');
			$pdf->SetSubject('订单列表');
			$pdf->SetKeywords('订单列表');
			$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH);
			$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
			$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
			$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
			$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
			$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
			$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
			$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
			$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
			$pdf->setLanguageArray($l);
			$pdf->SetFont('stsongstdlight', '', 20);
			$pdf->AddPage();
			//$pdf->write(0, $this->fetch ($template), '', 0, 'L', true, 0, false, false, 0);
			$pdf->writeHTML($this->fetch ('Yourphp/Tpl/Default/Public/billtemplate/'.$_POST['template']), true, 0, true, 0);
			$pdf->Output('example_038.pdf', 'I');
			
			
			
			
			
		}else{echo'no data';}
    }

	public function export()
	{
		header('Cache-Control: no-cache, must-revalidate');
		header("Content-type:application/vnd.ms-excel");
		header("Content-Disposition:attachment;filename=data.xls");




		$model = M(MODULE_NAME);
		$id=$model->getPk ();
		$this->assign ( 'pkid', $id );

		if (isset ( $_REQUEST ['order'] )) {
			$order = $_REQUEST ['order'];
		} else {
			$order = ! empty ( $sortBy ) ? $sortBy : $id;
		}
		if (isset ( $_REQUEST ['sort'])) {
			$_REQUEST ['sort']=='asc' ? $sort = 'asc' : $sort = 'desc';
		} else {
			$sort = $asc ? 'asc' : 'desc';
		}
		$website=$_REQUEST['website'];
		$_REQUEST ['sort'] = $sort;
		$_REQUEST ['order'] = $order;
		$keyword=$_REQUEST['keyword'];
		$searchtype=$_REQUEST['searchtype'];
		$groupid =intval($_REQUEST['groupid']);
		$catid =intval($_REQUEST['catid']);
		$posid =intval($_REQUEST['posid']);
		$typeid =intval($_REQUEST['typeid']);
		if(!empty($keyword) && !empty($searchtype)){
			$map[$searchtype]=array('like','%'.$keyword.'%');
		}
		if($website) $map['domain']=$website;
if($_REQUEST['startdate'] && $_REQUEST['enddate']){
//时间查询
		$_REQUEST['startdate']=strtotime($_REQUEST['startdate']);
		$_REQUEST['enddate']=strtotime($_REQUEST['enddate']);
		define('Halfofday',60*60*24-1);
		$_REQUEST['enddate']=$_REQUEST['enddate']+Halofday;
		$map['createtime']=array(array('gt',$_REQUEST['startdate']),array('lt',$_REQUEST['enddate'])) ;
}
		if($groupid)$map['groupid']=$groupid;
		if($catid)$map['catid']=$catid;
		if($posid)$map['posid']=$posid;
		if($typeid) $map['typeid']=$typeid;

		if(isset($_REQUEST['status']) && ( $_REQUEST['status']==='0' || $_REQUEST['status']>0)){
			$map['status']=intval($_REQUEST['status']);
		}else{
			unset($_REQUEST['status']);
		}

		$this->assign($_REQUEST);
		$this->assign('website',$website);
		//取得满足条件的记录总数
		$count = $model->where ( $map )->count ( $id );
		if ($count > 0) {

				$field=$this->module[$this->moduleid]['listfields'];
				$voList = $model->field($field)->where($map)->order( "`" . $order . "` " . $sort)->findAll ( );
				foreach($voList as $k=>$val){
					$val['productlist']=unserialize($val['productlist']);
					$voList[$k]['sublist']=$val['productlist'];
				}
				$this->assign ( 'list', $voList );
		}







        $this->display ();
	}
}
?>